// 配置信息
import { defineStore } from "pinia"
import { apiGeInitData, apiRecommendList } from '@/api/system.js'
import useUserStore from '../modules/user.js'

let useSystemStore = defineStore("systemStore", {
	state: () => {
		return {
			isLoading: false,
			recommendList: [], // 推荐列表
			systemConfig: null, // 全局配置信息
			isPersonalization: uni.getStorageSync('isPersonalization') !== false // 个性化推荐
		}
	},
	actions: {
		// 获取配置信息
		async getSystem() {
			try {
				this.isLoading = true;
				// 登录获取 code
				const loginRes = await new Promise((resolve, reject) => {
					uni.login({
						provider: 'weixin',
						success: resolve,
						fail: reject
					});
				});
				// 调用 API 获取 token
				const { code } = loginRes;
				const params = {
					user_terminal: 'weapp',
					code,
					appid: uni.getAccountInfoSync().miniProgram.appId || ""
				};
				const { data: { token, systemConfig } } = await apiGeInitData(params);
				const userStore = useUserStore();
				userStore.setToken(token?.access_token);
				this.systemConfig = systemConfig
				return 'ok';
			} catch (error) {
				console.error('获取系统配置失败:', error);
				throw error; // 重新抛出错误，让调用者处理
			} finally {
				this.isLoading = false; // 无论成功失败都重置加载状态
			}
		},
		setPersonalization(val) {
			this.isPersonalization = val
			uni.setStorageSync('isPersonalization', val)
		},
		// 获取推荐列表
		async getApiRecommendList() {
			try {
				const { data } = await apiRecommendList({
					page: 1,
					pageSize: 30
				})
				this.recommendList = data
				uni.setStorageSync('recommendList', data)
				return Promise.resolve('ok');
			} catch (error) {
				console.log(error, 'error');
			}
		}
	},
	getters: {},
})

export default useSystemStore